import {serve} from 'bun';
import * as path from 'node:path';
import {readFileSync} from 'node:fs';
import {
  CLOUD_POST,
  SERVER_BASE_URL,
  SERVER_PORT,
} from '../constant.ts';
import shell from 'shelljs';
import saveFilePiece from './utils/saveFilePiece.ts';
import {BASE_PATH, UTIL_PATH} from './constant.ts';

console.log(`本地url: http://localhost:${SERVER_PORT}/`);

function getContentType(filePath: string) {
  const ext = path.extname(filePath);

  if (ext === '.html') return 'text/html';

  if (ext === '.js') return 'text/javascript';

  return 'text/plain';
}

serve({
  websocket: undefined,
  port: SERVER_PORT,
  fetch(req) {
    const url = new URL(req.url);
    console.log(`[${req.method}]`, url.pathname);
    // 上传文件
    if (url.pathname === SERVER_BASE_URL + '/file') {
      return req.formData().then(res => {
        // 保存当前文件分片
        saveFilePiece(res);

        const data = JSON.stringify({success: true});
        const getLength = Buffer.byteLength;
        return new Response(data, {
          headers: {
            'Content-Type': 'application/json',
            'Content-Length': getLength(data).toString(),
          },
        });
      }).catch(err => {
        console.log(err);
      });
    }

    if (url.pathname === '/favicon.ico') return null;

    const filePath = path.join(
      BASE_PATH, url.pathname === '/' ? 'index.html' : url.pathname.replaceAll('..', ''));
    const file = readFileSync(filePath, 'utf8');
    return new Response(file, {
      headers: {
        'Content-Type': getContentType(filePath),
      },
    });
  },

  error(error) {
    console.error(error);
    return new Response(`<pre>${error}\n${error.stack}</pre>`, {
      headers: {
        'Content-Type': 'text/html',
      },
    });
  }
  ,
});

// shell.exec(`lt -p ${POST} --host https://loca.lt/ --subdomain huangwentao`)

// bore.exe
console.log('云端url:', `http://bore.pub:${CLOUD_POST}/`);
shell.exec(`${path.join(UTIL_PATH, 'bore.exe')} local ${SERVER_PORT} --to bore.pub --port ${CLOUD_POST}`);